package com.dst.controllers;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dst.dao.LoginSystemDao;
import com.dst.domain.LoginSystem;
import com.dst.form.LoginForm;


@Controller
@RequestMapping("login")
public class LoginController {
	
	@Autowired
	LoginSystemDao loginSystemDao;
	
	@RequestMapping(method = RequestMethod.GET)
	public String showForm(Map<String, LoginForm> model) {
		LoginForm loginForm = new LoginForm();
		model.put("loginForm", loginForm);
		return "loginform";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processForm(@Valid LoginForm loginForm, BindingResult result,
			Map<String, LoginForm> model) {
		//String userName = "UserName";
		//String password = "password";
		if (result.hasErrors()) {
			return "loginform";
		}
		loginForm = (LoginForm) model.get("loginForm");
		LoginSystem loginInfo = loginSystemDao.getLoginInfo(loginForm.getUserName(), loginForm.getPassword());
		if(loginInfo == null) {
//		if (!loginForm.getUserName().equals(userName)
//				|| !loginForm.getPassword().equals(password)) {
			
			result.addError(new ObjectError("invalidCredentials","Invalid User Name/ Password."));
			return "loginform";
		}
		model.put("loginForm", loginForm);
		return "loginsuccess";
	}

}
